package com.jinzhending.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinzhending.entity.WxUser;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @ProjectName: LieIdle
 * @Package: com.jinzhending.utils
 * @Author: huat
 * @Date: 2020/4/8 16:57
 * @Version: 1.0
 */
@Slf4j
public class JsonUtil {
    public static final ObjectMapper objectMapper=new ObjectMapper();

    /**
     * 将对象转为json
     * @param object  对象
     * @return json
     */
    public static String ObjectToString(Object object) {
        if(null==object){
            return null;
        }
        if(object.getClass()==String.class){
            return (String)object;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.info(object+"序列化出错"+e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将json转换成对象
     * @param json json字符串
     * @param tClass 类
     * @param <T> 泛型
     * @return 返回对象
     */
    public static <T> T toBean(String json,Class<T> tClass){
        try {
            return objectMapper.readValue(json,tClass);
        } catch (IOException e) {
            log.info(json+"转对象失败"+e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


}
